using KL.Core.Common.infrastructure;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;

namespace KL.Core.Extensions.Log;

public static class SerilogSetup
{
    public static void AddSerilogSetup(this IHostBuilder hostBuilder)
    {
        var loggerConfiguration = new LoggerConfiguration()
                .ReadFrom.Configuration(AppSettings.Configuration)
                //.Enrich.WithProperty("APP","EagExcellence") // 自定义属性
                //.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning) // 过滤掉 Microsoft.AspNetCore 
                //.MinimumLevel.Information()
                //.Enrich.FromLogContext()
                //输出到控制台
                .WriteTo.Console(restrictedToMinimumLevel: LogEventLevel.Information)
                //将日志保存到文件中
                .WriteTo.File("logs/GlobalInfoLogs_.log", 
                    restrictedToMinimumLevel: LogEventLevel.Information,
                    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Properties:j} {Message:lj}{NewLine}{Exception}",
                    rollingInterval: RollingInterval.Day)
                .WriteTo.File("logs/GlobalExceptionLogs_.log", 
                    restrictedToMinimumLevel: LogEventLevel.Error,
                    outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Properties:j} {Message:lj}{NewLine}{Exception}",
                    rollingInterval: RollingInterval.Day)
            ;
        Serilog.Log.Logger = loggerConfiguration.CreateLogger();
        hostBuilder
            .UseSerilog()
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders(); // 清除默认的日志提供程序
        
                logging.AddSerilog(); // 添加 Serilog 日志提供程序
                // logging.AddFilter("System", LogLevel.Error);
                // logging.AddFilter("Microsoft", LogLevel.Error);
            });;
    }
}